//
//  PACreateChartConfigVC.m
//  PilotSeries
//
//  Created by 黄立强 on 16/7/4.
//  Copyright © 2016年 leon.huang. All rights reserved.
//

#import "PACreateChartConfigVC.h"
#import "RangeListData.h"
#import "ChartConfig.h"
#import "PAWebSocketManager.h"
#import "PAChartConfigManager.h"
#import "PAGroupManager.h"
#import "PAAccountManager.h"
#import "PAParamVC.h"

@interface PACreateChartConfigVC ()
 @property (strong, nonatomic) NSMutableDictionary *paramters;
@end

@implementation PACreateChartConfigVC

#pragma mark - 懒加载
//- (NSMutableDictionary *)paramters
//{
//    if (_paramters == nil) {
//        _paramters = [[NSMutableDictionary alloc] init];
//    }
//    return _paramters;
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Create Chart";
    [self initializeForm];
    self.navigationItem.rightBarButtonItem  = [[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(configData:)];
}

-(void)initializeForm{
    XLFormDescriptor * form;
    XLFormSectionDescriptor * section;
    XLFormRowDescriptor * row;
    
    form = [XLFormDescriptor formDescriptor];
    //    form.assignFirstResponderOnShow = YES;
    section = [XLFormSectionDescriptor formSectionWithTitle:nil];
    
    XLFormRowDescriptor *infoRowDescriptor = [XLFormRowDescriptor formRowDescriptorWithTag:@"rangeName"rowType:XLFormRowDescriptorTypeInfo];
    infoRowDescriptor.title = @"rangeName";
    infoRowDescriptor.value = self.rangeData.name;
    [section addFormRow:infoRowDescriptor];
    
    // Name
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"chartName" rowType:XLFormRowDescriptorTypeText title:@"chartName"];
    [row.cellConfigAtConfigure setObject:@(NSTextAlignmentRight) forKey:@"textField.textAlignment"];
    
    row.value =@"";
    row.required = YES;
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"rowNames" rowType:XLFormRowDescriptorTypeMultipleSelector title:@"Rows"];
    
    row.selectorOptions =self.rangeData.rowNames==nil?@[]:self.rangeData.rowNames;
    row.required = YES;
    [section addFormRow:row];
    
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"columnNames" rowType:XLFormRowDescriptorTypeMultipleSelector title:@"Cols"];
    row.selectorOptions =self.rangeData.columnNames==nil?@[]:self.rangeData.columnNames;
    row.required = YES;
    [section addFormRow:row];
    // DateTime
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"startTime" rowType:XLFormRowDescriptorTypeDateTime title:@"startTime"];
    row.required = YES;
    row.value = [NSDate new];
    [section addFormRow:row];
    
    // DateTime
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"endTime" rowType:XLFormRowDescriptorTypeDateTime title:@"endTime"];
    [section addFormRow:row];
    
    // MaxRecords
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"maxRecords" rowType:XLFormRowDescriptorTypeNumber title:@"maxRecords"];
    [row.cellConfigAtConfigure setObject:@(NSTextAlignmentRight) forKey:@"textField.textAlignment"];
    row.value = @10000;
    [section addFormRow:row];
    
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"orderby" rowType:XLFormRowDescriptorTypeSelectorPush title:@"Orderby"];
    row.selectorOptions = @[@"DESC",@"ASC"];
    row.value = @"DESC";
    
    [section addFormRow:row];

    //params
    // TextFieldAndTextView
    row = [XLFormRowDescriptor formRowDescriptorWithTag:@"paramters" rowType:XLFormRowDescriptorTypeButton title:@"Paramters"];
    [row.cellConfig setObject:@(UITableViewCellAccessoryDisclosureIndicator) forKey:@"accessoryType"];
    [row.cellConfig setObject:@(NSTextAlignmentNatural) forKey:@"textLabel.textAlignment"];
    //    row.action.viewControllerClass = [ParamsViewController class];
    __typeof(self) __weak weakSelf = self;
    row.action.formBlock = ^(XLFormRowDescriptor * sender){
        
        PAParamVC *pvc = [[PAParamVC alloc] init];
        pvc.block = ^(NSMutableDictionary *params){
             weakSelf.paramters = params;
        };
        [self.navigationController pushViewController:pvc animated:YES];

        
    };
    [section addFormRow:row];
    
    [form addFormSection:section];
    self.form = form;
}

- (void)processChartConfig:(ChartConfig *)chartConfig isAdd:(BOOL) isAdd
{
    //1.发送config
    if(![[PAWebSocketManager sharedInstance] sendMsg:chartConfig.config.mj_JSONString]) return;
    
    //2.保存到currentChart
    BOOL isUpdate = [PAChartConfigManager saveChartConfig:chartConfig];
    
    //3.查看是否选中群组，如果选中，则添加到群组中
    NSString *groupName = [PAAccountManager loadCurrentGroupName];
    if (groupName!=nil &&![groupName isEqualToString:@""]) {
        
       [PAGroupManager addChartConfig:chartConfig.chartName toGroup:groupName];
    }
     //4.新增或者修改chartConfigs
    if (isAdd) {
        [[PAAppContext sharedInstance].chartConfigs addObject:chartConfig];
    }else{
        NSInteger index = [[PAAppContext sharedInstance].chartNames indexOfObject:chartConfig.chartName];
        [[PAAppContext sharedInstance].chartConfigs replaceObjectAtIndex:index withObject:chartConfig];
    }
    //5.通知collectionview 添加graph
    if (isUpdate) {
          [[NSNotificationCenter defaultCenter] postNotificationName:PACurrentChartUpdateNotification object:nil userInfo:@{@"chartConfig":chartConfig}];
    }else{
        
        [[NSNotificationCenter defaultCenter] postNotificationName:PAChartListVCItemClickNotification object:nil userInfo:@{@"chartConfig":chartConfig}];
    }
  
    
    //6.
    [self.navigationController popToRootViewControllerAnimated:YES];
   self.splitViewController.preferredDisplayMode = UISplitViewControllerDisplayModePrimaryHidden;
}

-(void)configData:(UIBarButtonItem *)buttonItem
{
    
    if (![self validateDatas]) {
        return;
    }
    
    XLFormRowDescriptor * row = [self.form formRowWithTag:@"chartName"];

    NSDictionary *dic = [self formValues];
    NSMutableDictionary *mdic = [dic mutableCopy];
    if (self.paramters!=nil) {
        mdic[@"paramters"] =self.paramters;
    }else{
        [mdic removeObjectForKey:@"paramters"];
    }
    

    if (dic[@"startTime"]!=nil && ![dic[@"startTime"] isKindOfClass:[NSNull class]]) {
        mdic[@"startTime"] = [dic[@"startTime"] dateWithFormat:@"yyyy-MM-dd hh:mm:ss"];
    }else{
        mdic[@"startTime"] = [[NSDate new] dateWithFormat:@"yyyy-MM-dd hh:mm:ss"];
    }
    if (dic[@"endTime"]!=nil && ![dic[@"endTime"] isKindOfClass:[NSNull class]]) {
        mdic[@"endTime"] = [dic[@"endTime"] dateWithFormat:@"yyyy-MM-dd hh:mm:ss"];
    }else{
        mdic[@"endTime"] = @"";
    }

    ChartConfig *chartConfig = [ChartConfig new];
    NSMutableDictionary *mConfig = [NSMutableDictionary new];
    mConfig[CONFIG_KEY_CONFIGSOURCE] = w_cofingSource;
    mConfig[CONFIG_KEY_HOST] = [PAAppContext sharedInstance].w_host;
    mConfig[CONFIG_KEY_PORT] = [NSNumber numberWithLong:[PAAppContext sharedInstance].w_port];
    mConfig[CONFIG_KEY_TYPE] = @"command";
    mConfig[CONFIG_KEY_COMMAND] = @"config";
    mConfig[CONFIG_KEY_CHARTNAME] =  row.value;
    mConfig[CONFIG_KEY_TITLE] = row.value;
     mConfig[CONFIG_KEY_GRAPHTYPE] = w_graphType;
    mConfig[CONFIG_KEY_APPID] =[PAAppContext sharedInstance].appid;
    chartConfig.chartName = row.value;
    chartConfig.config = mConfig;
    mConfig[CONFIG_KEY_RANGECONFIG] =  mdic;

    //如果本地已经有该config了，则提醒用户
    if ([[PAAppContext sharedInstance].chartNames containsObject:row.value]) {
        
        [UIAlertView alertWithCallBackBlock:^(NSInteger buttonIndex) {
            if (buttonIndex==1) {
                
             [self processChartConfig:chartConfig isAdd:NO];
                
                
            }else if (buttonIndex==0){
                
                
            }
            
        } title:@"Conifrim Chart" message:@"Already have the chart,are you meaning to override it?" cancelButtonName:@"cancel" otherButtonTitles:@"override", nil];
        
    }else{
        
        
        [self processChartConfig:chartConfig isAdd:YES];
        
    }
   
    
    
}

-(BOOL)validateDatas{
    NSArray * array = [self formValidationErrors];
    if (array ==nil || array.count<1) {
        return YES;
    }else{
        [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            XLFormValidationStatus * validationStatus = [[obj userInfo] objectForKey:XLValidationStatusErrorKey];
            UITableViewCell * cell = [self.tableView cellForRowAtIndexPath:[self.form indexPathOfFormRow:validationStatus.rowDescriptor]];
            [cell shake];
            
        }];
        return NO;
    }
    
    
    
}
@end
